'use strict';

const Controller = require('egg').Controller;

class TicketController extends Controller {
  async orderTicket() {
    const ctx = this.ctx;
    const app = this.app;
    const body = ctx.request.body;
    const { conversation_id, staff_id } = body;
    const nsp = app.io.of('/manager');

    try {
      await ctx.service.conversation.setConversationStaff(conversation_id, staff_id);
      const conversation = await ctx.service.conversation.getConversationById(conversation_id);
      const { user_id } = conversation;
      this.ctx.body = {
        code: 200,
        conversation,
        msg: '接单成功',
      };

      await nsp.emit(`manager_${user_id}`, {
        type: 2, // 有客服接单了，让其连入 websocket
        conversation,
      }); // 通知所有客服需要更新消息列表
    } catch (e) {
      this.ctx.body = {
        code: 500,
        msg: '服务端出错',
      };
    }
  }

  async setTicketStaff() {
    const ctx = this.ctx;
    const body = ctx.request.body;
    const { conversation_id, staff_id } = body;

    try {
      await ctx.service.conversation.setConversationStaff(conversation_id, staff_id);
      const conversation = await ctx.service.conversation.getConversationById(conversation_id);
      this.ctx.body = {
        code: 200,
        conversation,
        msg: '工单分配成功',
      };
    } catch (e) {
      this.ctx.body = {
        code: 500,
        msg: '服务端出错',
      };
    }
  }

  async evaluate() {
    const ctx = this.ctx;
    const body = ctx.request.body;
    const { conversation_id, score, info_id } = body;

    try {
      const conversation = await ctx.service.conversation.getConversationById(conversation_id);
      const { staff_id } = conversation;


      const newConversation = await ctx.service.conversation.evaluate(conversation_id, score);

      await ctx.service.conversationInfo.evaluate(info_id, score);


      const user = await ctx.service.user.evaluate(staff_id, score);
      ctx.body = {
        code: 200,
        conversation: newConversation,
        user,
        msg: '评价成功',
      };
    } catch (e) {
      this.ctx.body = {
        code: 500,
        msg: '服务端出错',
      };
    }
  }
}

module.exports = TicketController;
